<?php

namespace app\admin\controller\warehouse;

use app\common\controller\Backend;
use Think\Db;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Outbound extends Backend
{
    
    /**
     * Outbound模型对象
     * @var \app\admin\model\warehouse\Outbound
     */
    protected $model = null;
    protected $searchFields = 'id,product_bn,batch';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\warehouse\Outbound;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['warehouse','location','products'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['warehouse','location','products'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $where['bn'] = $row->product_bn;
        $pro = Db::name('products')->where($where)->find();
        $row->name = $pro['name'];
        $this->assignconfig('row', $row);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $post = json_decode($params['batch'],true);
                $params = array(
                    'product_bn' => $params['product_bn'],
                    'batch' => $post['batch'],
                    'locationid' => $post['locationid'],
                    'warehouseid' => $post['warehouseid'],
                    'num' => $params['num'],
                );
                //判断是否可以出库
                $where2['product_bn'] = $params['product_bn'];
                $where2['batch'] = $params['batch'];
                $where2['locationid'] = $params['locationid'];
                $where2['warehouseid'] = $params['warehouseid'];
                $stockitems_model = new \app\admin\model\warehouse\Stockitems;
                $stockitems_model_res = $stockitems_model->where($where2)->find();
                if(!$stockitems_model_res || empty($stockitems_model_res)){
                    $this->error(__('Operation failed', ''));
                }else{
                    if($params['num'] > $stockitems_model_res['num']){
                        $this->error(__('Inventory shortage', ''));
                    }elseif($params['num'] <= 0){
                        $this->error(__('Please enter the correct quantity', ''));
                    }
                }
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                $res = false;
                $ress = false;
                Db::startTrans();
                try {
                    //更新总库存,明细表以及库存表
                    $stock_model = new \app\admin\model\warehouse\Stock;
                    //更新明细表
                    $where11['product_bn'] = $params['product_bn'];
                    $where11['batch'] = $params['batch'];
                    $where11['warehouseid'] = $params['warehouseid'];
                    $where11['locationid'] = $params['locationid'];
                    $stockitems_res = $stockitems_model->where($where11)->find();
                    if(!empty($stockitems_res) && $stockitems_res) {//更新
                        $stockitems_data['num'] = $stockitems_res->num - $params['num'];
                        $stockitems_data['updatetime'] = time();
                        $ress = $stockitems_model->where($where11)->update($stockitems_data);
                    }
                    //查询是否已存在数据
                    $where['product_bn'] = $params['product_bn'];
                    $stock_res = $stock_model->where($where)->find();
                    if(!empty($stock_res) && $stock_res){//更新
                        //是否采用模型验证
                        if ($this->modelValidate) {
                            $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                            $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                            $this->model->validateFailException(true)->validate($validate);
                        }
                        $result = $this->model->allowField(true)->save($params);
                        $ids = json_decode($stock_res->outboundids,true);
                        $ids[] = $this->model->id;
                        $data['outboundids'] = json_encode($ids);
                        $data['num'] = $stock_res->num - $params['num'];
                        $where1['id'] = $stock_res->id;
                        $res = $stock_model->where($where1)->update($data);
                        Db::commit();
                    }else{
                        Db::rollback();
                        $this->error(__('No rows were inserted', ''));
                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false && $res !== false && $ress !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }
    /**
     * 批次号batch搜索
     *
     * @internal
     */
    public function selectbatch()
    {
        $model = new \app\admin\model\warehouse\Stockitems;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 99999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'batch';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $model->where($this->dataLimitField, 'in', $adminIds);
            }
            $datalist = $model->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->field($this->selectpageFields)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    'warehouseid'          => json_encode(array(
                        'batch'     => $item['batch'],
                        'locationid'     => $item['locationid'],
                        'warehouseid'     => $item['warehouseid'],
                        'num'           => $item['num']
                    )),
                    'batch'           => '批次号:'.$item['batch'].'&nbsp&nbsp&nbsp&nbsp数量：'.$item['num'].'&nbsp&nbsp&nbsp&nbsp库位:'.$item['locationid'].'&nbsp&nbsp&nbsp&nbsp仓库:'.$item['warehouseid'],
                    'pid'       => isset($item['pid']) ? $item['pid'] : 0
                ];
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
    /**
     * 批次号batch搜索
     *
     * @internal
     */
    public function selectwarehouse(){
        $model = new \app\admin\model\warehouse\Stockitems;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 99999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'warehouseid';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $model->where($this->dataLimitField, 'in', $adminIds);
            }
            $datalist = $model->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->field($this->selectpageFields)
                ->select();
            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    $field      => isset($item[$field]) ? $item[$field] : '',
                    'pid'       => isset($item['pid']) ? $item['pid'] : 0
                ];
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        $warehouse_model = new \app\admin\model\warehouse\Warehouse;
        if(!empty($list)){
            foreach($list as $key => $val){
                $where1['id'] = $val['warehouseid'];
                $warehouse_data = $warehouse_model->where($where1)->find();
                $list[$key]['warehouseid'] = $warehouse_data['name'];
                $list[$key]['id'] = $warehouse_data['id'];
            }
        }
        return json(['list' => $list, 'total' => $total]);
    }
    /*
     * 获取数量
     * */
    public function findnum(){
        $custom = (array)$this->request->request("custom/a");
        $model = new \app\admin\model\warehouse\Stockitems;
        $model_res = $model->where($custom)->find();
        return $model_res;
    }
}
